package com.nut.article.service.impl;

import com.nut.article.common.Result;
import com.nut.article.entity.SysFile;
import com.nut.article.mapper.SysFileMapper;
import com.nut.article.service.SysFileService;
import com.nut.article.util.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.ThreadLocalRandom;

@Slf4j
@Service
public class SysFileServiceImpl implements SysFileService {

    public static final String HOST = "http://8.140.53.78/images/";

    @Autowired
    private SysFileMapper sysFileMapper;

    public static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyMMddHHmmss");

//    public static final String filePath = "/opt/images/";
    public static final String filePath = "/data/images/";

    @Override
    public Result<String> upload(MultipartFile multipartFile) {

        String originalFilename = multipartFile.getOriginalFilename();
        String ext = originalFilename.substring(originalFilename.lastIndexOf(".") + 1).toLowerCase();

        try {
            String fileName = upload(multipartFile, ext);
            String url = HOST + fileName;
            SysFile ossFile = new SysFile();
            ossFile.setName(fileName);
            ossFile.setUrl(url);
            ossFile.setSize(multipartFile.getSize());
            ossFile.setExt(ext);
            sysFileMapper.insert(ossFile);
            return Result.ok(url);
        } catch (Exception e) {
            log.error("upload_error", e);
            return Result.fail(e.getMessage());
        }
    }

    private static String generateFileName(String ext) {
        return FORMATTER.format(LocalDateTime.now()) + (100 + ThreadLocalRandom.current().nextInt(899)) + "." + ext;
    }

    private String upload(MultipartFile file, String ext) {
        try {
            String fileName = generateFileName(ext);

            fileName = DateUtil.getNowMonth() + "/" + fileName;
            String path = filePath  + fileName;
            // getCanonicalFile 可解析正确各种路径
            File dest = new File(path).getCanonicalFile();
            // 检测是否存在目录
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            // 文件写入
            file.transferTo(dest);
            return fileName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) throws Exception {

//        System.out.println(LocalDate.now().getYear());
//        System.out.println(LocalDate.now().getMonthValue());

    }
}
